/**
 * 北京中流科技有限公司 版权所有
 * http://www.chinasoa.com.cn
 */
package cn.com.chinasoa.course.subscribe;

import java.io.IOException;

import javax.persistence.EntityManager;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;

import cn.com.chinasoa.course.subscribe.model.PrivilegeStrategy;
import cn.com.chinasoa.course.subscribe.util.DataTypeUtil;
import cn.com.chinasoa.course.subscribe.util.EntityManagerHelper;

import com.x4ee.soa.portal.framework.core.ActionConfig;
import com.x4ee.soa.portal.framework.core.ActionFilter;
import com.x4ee.soa.portal.framework.core.BaseRequestFilter;

/**
 * @author 刘洋(liuyang@chinasoa.com.cn)
 * 2007-11-5下午03:04:09
 */
public class PrivilegeStrategyOperateActionFilter extends BaseRequestFilter
		implements ActionFilter {

	private static String SUCCESS = "success";
	private static String FAILED = "error";

	public String process(ActionRequest actionRequest, ActionResponse actionResponse, ActionConfig actionConfig) 
		throws PortletException, IOException {
		
		long privilegeStrategyId = DataTypeUtil.parseLong(actionRequest.getParameter("privilegeStrategyId"));
		String cmd = actionRequest.getParameter("cmd");

		String description = actionRequest.getParameter("description");
		String discount = actionRequest.getParameter("discount");

		boolean success = false;
		if((privilegeStrategyId>0)&&(cmd!=null)&&(description!=null)&&(discount!=null)){
			int discountInt= DataTypeUtil.parseInt(discount);
			if((discountInt>0)&&(discountInt<=100)){
				if(cmd.equals("edit")){
					EntityManager em = EntityManagerHelper.getEntityManager();
					em.getTransaction().begin();
					PrivilegeStrategy vPrivilegeStrategy = em.find(PrivilegeStrategy.class, privilegeStrategyId);
					if(vPrivilegeStrategy!=null){
						vPrivilegeStrategy.setDescription(description);
						vPrivilegeStrategy.setDiscount(discountInt);
					}
					em.getTransaction().commit();
					EntityManagerHelper.closeEntityManager();
					success = true;
				}
			}else{
				success = false;
			}
		}else{
			if((privilegeStrategyId>0)&&(cmd!=null)&&(cmd.equals("delete"))){
				EntityManager em = EntityManagerHelper.getEntityManager();
				em.getTransaction().begin();
				PrivilegeStrategy vPrivilegeStrategy = em.find(PrivilegeStrategy.class, privilegeStrategyId);
				if(vPrivilegeStrategy!=null){
					em.remove(vPrivilegeStrategy);
				}
				em.getTransaction().commit();
				EntityManagerHelper.closeEntityManager();
				success = true;				
			}else{
				success = false;
			}
		}
		if(success)return SUCCESS;
		else return FAILED;
	}
}
